package org.frame.auth.common.handle;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.frame.auth.common.utils.ServletUtils;
import org.frame.auth.token.TokenService;
import org.frame.common.core.AjaxResult;
import org.frame.common.core.HttpStatus;
import org.frame.common.core.StringUtils;
import org.frame.common.core.constants.Constants;
import org.frame.common.core.entity.TokenUser;
import org.frame.common.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;

/**
 * 自定义退出处理类 返回成功
 * 
 * @author ruoyi
 */
@Slf4j
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
	@Autowired
	private TokenService tokenService;
	@Autowired
	private RedisCache redisCache;

	/**
	 * 退出处理
	 * 
	 * @return
	 */
	@Override
	public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		try {
			TokenUser loginUser = tokenService.getTokenUser(request);
			if (StringUtils.isNotNull(loginUser)) {
				String key = Constants.LOGIN_TOKEN_KEY + loginUser.getToken();
				redisCache.deleteObject(key);
				// 记录用户退出日志
				// AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
			}
		} catch (Exception e) {
			log.error("退出异常", e);
		}
		ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(HttpStatus.SUCCESS, "退出成功")));
	}
}
